import { defHttp } from '@/utils/http/axios';
import { isFunction } from '@/utils/is';
import { downloadBlob } from '@/utils/file/download';

export function getData(api, params) {
  if (isFunction(api)) {
    return api(params);
  }
  const strApiArr = api.split('@');
  if (strApiArr.length === 1) {
    return defHttp.get({ url: api, params });
  }
  if (strApiArr.length === 2) {
    const method = strApiArr[0];
    return defHttp[method]({ url: strApiArr[1], params });
  }
  console.error('api配置可能不正确 1 promise请求 2 method:url||url(get)');
}
function doDownLoad(api, method, params) {
  return new Promise<void>((resolve, reject) => {
    defHttp[method](
      { responseType: 'blob', url: api, params },
      { isReturnNativeResponse: true }
    )
      .then((res) => {
        downloadBlob(res);
        resolve();
      })
      .catch(() => {
        reject();
      });
  });
}
export function exportData(api, params) {
  if (isFunction(api)) {
    return api(params);
  }
  const strApiArr = api.split('@');
  if (strApiArr.length === 1) {
    return doDownLoad(api, 'get', params);
  }
  if (strApiArr.length === 2) {
    const method = strApiArr[0];
    return doDownLoad(strApiArr[1], method, params);
  }
}
export function delData(api, params) {
  if (isFunction(api)) {
    return api(params);
  } else {
    return defHttp.post({ url: api, params });
  }
}
